<!--
  优化后的工单创建示例组件
  演示：防重复提交、乐观更新、错误处理
-->
<template>
  <div class="optimized-ticket-create">
    <el-card header="创建工单（优化版）">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="formData.title" 
            placeholder="请输入工单标题"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :rows="4"
            placeholder="请输入工单描述"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-select v-model="formData.priority" :disabled="loading">
            <el-option label="低" value="LOW" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="高" value="HIGH" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" :disabled="loading">
            <el-option label="技术支持" value="TECHNICAL" />
            <el-option label="功能请求" value="FEATURE" />
            <el-option label="Bug报告" value="BUG" />
            <el-option label="咨询" value="INQUIRY" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading"
            :disabled="!canSubmit"
            @click="handleSubmit"
          >
            <template v-if="loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              提交中...
            </template>
            <template v-else>
              创建工单
              <span v-if="!canSubmit && remainingTime > 0" class="countdown">
                ({{ remainingTime }}s后可重试)
              </span>
            </template>
          </el-button>

          <el-button @click="handleReset" :disabled="loading">
            重置
          </el-button>

          <el-button @click="showOptimisticTickets" type="info">
            查看Pending工单 ({{ ticketsStore.optimisticTickets.length }})
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 功能说明 -->
      <el-divider />
      <div class="feature-info">
        <h4>✨ 优化功能演示：</h4>
        <ul>
          <li>✅ <strong>乐观更新</strong>：点击创建后，工单立即显示在列表中（pending状态）</li>
          <li>✅ <strong>防重复提交</strong>：提交后{{ submitDebounceTime / 1000 }}秒内无法重复提交</li>
          <li>✅ <strong>自动重试</strong>：网络错误会自动重试（1秒、3秒、5秒间隔）</li>
          <li>✅ <strong>失败回滚</strong>：如果创建失败，pending工单会自动移除</li>
          <li>✅ <strong>友好提示</strong>：错误信息清晰，支持手动重试</li>
        </ul>
      </div>

      <!-- 实时状态 -->
      <el-divider />
      <div class="status-panel">
        <el-descriptions title="实时状态" :column="2" border>
          <el-descriptions-item label="提交状态">
            <el-tag :type="loading ? 'warning' : 'success'">
              {{ loading ? '提交中' : '空闲' }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item label="可否提交">
            <el-tag :type="canSubmit ? 'success' : 'danger'">
              {{ canSubmit ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item label="倒计时">
            {{ remainingTime > 0 ? `${remainingTime}秒` : '无' }}
          </el-descriptions-item>
          
          <el-descriptions-item label="Pending工单">
            {{ ticketsStore.optimisticTickets.length }}个
          </el-descriptions-item>
          
          <el-descriptions-item label="总工单数">
            {{ ticketsStore.ticketStats.total }}个
          </el-descriptions-item>
          
          <el-descriptions-item label="最后提交">
            {{ lastSubmitTimeStr }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- Pending工单列表对话框 -->
    <el-dialog v-model="dialogVisible" title="Pending工单" width="600px">
      <el-table :data="ticketsStore.optimisticTickets" max-height="400">
        <el-table-column prop="id" label="临时ID" width="180" />
        <el-table-column prop="title" label="标题" />
        <el-table-column label="状态">
          <template #default>
            <el-tag type="warning">
              <el-icon class="is-loading"><Loading /></el-icon>
              提交中
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useFormSubmit } from '@/composables/useSubmit'
import { useTicketsStore } from '@/store/ticketsOptimized'
import { Loading } from '@element-plus/icons-vue'

const ticketsStore = useTicketsStore()
const formRef = ref(null)
const dialogVisible = ref(false)

// 防抖时间
const submitDebounceTime = 2000

// 表单数据
const formData = ref({
  title: '',
  description: '',
  priority: 'MEDIUM',
  category: 'TECHNICAL'
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在5-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 10, message: '描述至少10个字符', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 使用增强的表单提交hook
const { 
  loading, 
  canSubmit, 
  remainingTime,
  submitWithValidation, 
  resetForm 
} = useFormSubmit(
  formRef,
  async (data) => {
    console.log('📝 提交表单数据:', data)
    
    // 使用乐观更新的store
    const result = await ticketsStore.createTicket(data)
    
    if (!result.success) {
      throw new Error(result.message)
    }
    
    return result.data
  },
  {
    debounceTime: submitDebounceTime,
    successMessage: '工单创建成功！',
    errorMessage: '工单创建失败',
    showMessage: true,
    onSuccess: (result) => {
      console.log('✅ 创建成功，返回数据:', result)
      // 重置表单
      resetForm()
    },
    onError: (error) => {
      console.error('❌ 创建失败:', error)
    }
  }
)

// 提交处理
const handleSubmit = async () => {
  await submitWithValidation(formData.value)
}

// 重置处理
const handleReset = () => {
  resetForm()
}

// 显示pending工单
const showOptimisticTickets = () => {
  dialogVisible.value = true
}

// 最后提交时间字符串
const lastSubmitTimeStr = computed(() => {
  if (ticketsStore.lastSubmitTime === 0) {
    return '从未'
  }
  
  const time = new Date(ticketsStore.lastSubmitTime)
  return time.toLocaleTimeString('zh-CN')
})
</script>

<style scoped>
.optimized-ticket-create {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.countdown {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}

.feature-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.feature-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.feature-info ul {
  margin: 0;
  padding-left: 20px;
}

.feature-info li {
  margin: 8px 0;
  line-height: 1.6;
}

.status-panel {
  margin-top: 15px;
}

.el-icon.is-loading {
  margin-right: 5px;
}
</style>

